const app = getApp();
const actions = require('../../../../redux/actions');
const { Logger } = require('../../logger');

const Steps = {
  Guide: 0,
  InputTargetWiFi: 1,
  InputDeviceWiFi: 2,
  DoConfig: 3,
  Success: -1,
  Fail: -2,
};

const WifiStatus = {
  UDP_CONNECTED: 0,
  UDP_GET_SSID_AND_PWD: 1,
  DEVICE_CONNECTED_SUCCESS: 2,
  DEVICE_CONNECTED_FAIL: 3
};

Component({
  properties: {
    title: {
      type: String,
    },

    errorTips: {
      type: Array,
    },

    needDeviceAp: {
      type: Boolean,
      value: false,
    },
  },

  data: {
    step: Steps.Guide,
    isReady: true,
    curConnStep: 0,
    ssid: '',
    password: '',
    udp: '',
    port: 0,
    isFirst: true,
  },

  attached() {
    app.wifiConfLogger = new Logger();
    wx.startWifi();
  },

  detached() {
    app.wifiConfLogger = null;
    wx.stopWifi();
    actions.resetWifiList();
  },

  methods: {
    onGuideComplete() {
      this.setData({ step: Steps.InputTargetWiFi });
    },

    onTargetWifiInputComplete(e) {
      this.targetWifi = e.detail.wifi;
      if (this.data.needDeviceAp) {
        // SoftAP配网：需要先连接到设备热点
        this.setData({
          step: Steps.InputDeviceWiFi,
          ssid:this.targetWifi.SSID,
          password: this.targetWifi.password
        });
      }
    },

    onDeviceWifiInputComplete() {
      // SoftAP配网：已连接到设备热点，开始配网
      this.startConfig();
    },

    onBack() {
      wx.navigateBack();
    },

    startConfig() {
      // 切换到开始配网页面
      this.setData({
        step: Steps.DoConfig,
      });

      console.log("startConfig");
      if (this.data.isFirst) {
        let udp = wx.createUDPSocket();
        this.data.isFirst = true;
        this.data.udp = udp;
        this.data.port = udp.bind();
      }
      let password = this.data.password;
      let ssid = this.data.ssid;
      let port = this.data.port;

      let message = JSON.stringify({
        port,
        password,
        ssid
      });

      // 发送数据到UDP服务，IP地址为“192.168.4.1”，端口号为 8266
      this.data.udp.send({
        address: '192.168.4.1',
        port: 8266,
        message
      });



      // 监听UDP响应数据
      this.data.udp.onMessage((res) => {
        console.log("get data from esp module");
        console.log(res);
        //字符串转换，很重要
        let unit8Arr = new Uint8Array(res.message);
        let encodedString = String.fromCharCode.apply(null, unit8Arr);
        let data = decodeURIComponent(escape((encodedString)));
        console.log("data:", data);
        let str = JSON.parse(data);
        switch (str.code) {
          case WifiStatus.UDP_CONNECTED:
            this.setData({curConnStep: 1});
            break;
          case WifiStatus.UDP_GET_SSID_AND_PWD:
            this.setData({curConnStep: 2});
            break;
          case WifiStatus.DEVICE_CONNECTED_SUCCESS:
            this.setData({curConnStep: 3});
            break;
          case WifiStatus.DEVICE_CONNECTED_FAIL:
            wx.showModal({
              title: '配网失败',
              content: '试试重启一下设备重新配网',
              showCancel: false,
              confirmText: '我知道了',
              success: () => {
                this.setData({
                  step: Steps.Fail,
                  logs: this.logger.toString(),
                });
              },
            });
            break;
        }
      });
    },
  },
});
